﻿using System;
using System.Linq;
using Abp.Configuration.Startup;
using Abp.MultiTenancy;
using Abp.Runtime;
using Abp.Runtime.Session;

namespace KelonProud.Extensions
{
    public interface IAbpSessionExtension : IAbpSession
    {
        string UserName { get; }

        string UserDisplayName { get; }

        int EditionId { get; }

    }

    public class AbpSessionExtension : ClaimsAbpSession, IAbpSessionExtension
    {
        public AbpSessionExtension(IPrincipalAccessor principalAccessor, IMultiTenancyConfig multiTenancy, ITenantResolver tenantResolver, IAmbientScopeProvider<SessionOverride> sessionOverrideScopeProvider) : base(principalAccessor, multiTenancy, tenantResolver, sessionOverrideScopeProvider)
        {
        }

        public string UserName => GetClaimValue(HonkSoftClaimTypes.UserName);
        public string UserDisplayName => GetClaimValue(HonkSoftClaimTypes.UserDisplayName);
        public int EditionId => GetClaimValue(HonkSoftClaimTypes.EditionId).ToInt32();

        private string GetClaimValue(string claimType)
        {
            var claimsPrincipal = PrincipalAccessor.Principal;

            var claim = claimsPrincipal?.Claims.FirstOrDefault(c => c.Type == claimType);
            if (string.IsNullOrEmpty(claim?.Value))
                return null;

            return claim.Value;
        }
    }

    public class HonkSoftClaimTypes
    {
        public const string UserName = "dragon_applocation_UserName";
        public const string UserDisplayName = "dragon_applocation_UserDisplayName";
        public const string EditionId = "dragon_applocation_EditionId";
    }
}
